
import { useNavigate } from "react-router-dom";
import { useEffect, useState, useCallback } from 'react';
import axios from '../../api/http';

function Index() {
  const nav = useNavigate();
  const [selectedDepartment] = useState('门诊外一科');
  const [selectedDate, setSelectedDate] = useState('周一 今日');
  const [selectedMonth] = useState('2020年1月');
  const [doctorList, setDoctorList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  type Doctor = { 
    doctorid?: string|number; 
    id?: string|number; 
    doctorname?: string; 
    name?: string; 
    doctorimage?: string; 
    avatar?: string; 
    doctorstate?: string; 
    doctortitle?: string; 
    socoadmin?: string; 
    doctorministre?: string; 
    doctorcity?: string; 
    doctorprice?: number; 
    price?: number; 
    rating?: number; 
    flags?: number; 
    views?: number;
    hospital?: string;
    department?: string;
    specialty?: string;
    availableSlots?: number;
    isFullyBooked?: boolean;
  }

  const handleBack = () => {
    nav(-1);
  };

  // const handleMoreOptions = () => {
  //   // 处理更多选项
  //   console.log('更多选项');
  // };

  // const handleTarget = () => {
  //   // 处理目标功能
  //   console.log('目标功能');
  // };

  const fetchDoctors = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = { 
        pageCode: 1, 
        pageSize: 20,
        department: selectedDepartment,
        date: selectedDate
      };
      
      const res = await axios.get('/doctor/list', { params }) as unknown as { data?: Doctor[]; list?: Doctor[] } | Doctor[];
      const data = (Array.isArray(res) ? res : (res?.data || res?.list || [])) as Doctor[];
      setDoctorList(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('获取数据失败:', error);
      // 使用模拟数据
      const mockData: Doctor[] = [
        {
          id: 1,
          doctorname: '刘医生',
          doctorimage: 'https://via.placeholder.com/60x60/4A90E2/FFFFFF?text=刘',
          doctortitle: '主任医师',
          socoadmin: '门诊外一科',
          specialty: '肛肠外科(肛肠良性基本),结直肠微创手...',
          availableSlots: 20,
          isFullyBooked: false
        },
        {
          id: 2,
          doctorname: '杨医生',
          doctorimage: 'https://via.placeholder.com/60x60/7ED321/FFFFFF?text=杨',
          doctortitle: '副主任医师',
          socoadmin: '门诊外一科',
          specialty: '肛肠外科(肛肠良性基本),结直肠微创手...',
          availableSlots: 10,
          isFullyBooked: false
        },
        {
          id: 3,
          doctorname: '章医生',
          doctorimage: 'https://via.placeholder.com/60x60/F5A623/FFFFFF?text=章',
          doctortitle: '主任医师',
          socoadmin: '门诊外一科',
          specialty: '肛肠外科(肛肠良性基本),结直肠微创手...',
          availableSlots: 30,
          isFullyBooked: false
        },
        {
          id: 4,
          doctorname: '章医生',
          doctorimage: 'https://via.placeholder.com/60x60/FF6B6B/FFFFFF?text=章',
          doctortitle: '副主任医师',
          socoadmin: '门诊外一科',
          specialty: '肛肠外科(肛肠良性基本),结直肠微创手...',
          availableSlots: 0,
          isFullyBooked: true
        }
      ];
      setDoctorList(mockData);
    } finally {
      setLoading(false);
    }
  }, [selectedDepartment, selectedDate]);

  useEffect(() => {
    fetchDoctors();
  }, [fetchDoctors]);

  const handleDepartmentChange = () => {
    // 处理科室选择
    console.log('选择科室');
  };

  const handleMonthChange = () => {
    // 处理月份选择
    console.log('选择月份');
    
    
  };

  const handleDateChange = (date: string) => {
    setSelectedDate(date);
  };

  const handleAppointment = (doctor: Doctor) => {
    if (doctor.isFullyBooked) {
      return; // 已约满，不处理点击
    }
    const doctorId = doctor.doctorid || doctor.id;
    nav(`/detail?id=${encodeURIComponent(String(doctorId))}`);
  };

  return (
    <div style={{ width: '100vw', minHeight: '100vh', background: '#fff' }}>
      {/* 顶部导航栏 */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '12px 16px',
        background: '#fff',
        borderBottom: '1px solid #f0f0f0'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <div 
            onClick={handleBack}
            style={{ 
              fontSize: '20px', 
              cursor: 'pointer',
              color: '#333'
            }}
          >
            ‹
          </div>
          <div style={{ fontSize: '18px', fontWeight: 600, color: '#333' }}>
            医生列表
          </div>
        </div>     
      </div>

      {/* 科室和日期选择 */}
      <div style={{ padding: '16px', background: '#fff' }}>
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'space-between',
          marginBottom: '12px'
        }}>
          <div 
            onClick={handleDepartmentChange}
            style={{ 
              fontSize: '16px', 
              fontWeight: 500, 
              color: '#333',
              cursor: 'pointer'
            }}
          >
            {selectedDepartment}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span style={{ fontSize: '16px' }}>📅</span>
            <div 
              onClick={handleMonthChange}
              style={{ 
                fontSize: '16px', 
                color: '#333',
                cursor: 'pointer'
              }}
            >
              {selectedMonth}
            </div>
          </div>
        </div>

        {/* 日期选择 */}
        <div style={{ display: 'flex', gap: '8px', overflowX: 'auto' }}>
          <div 
            onClick={() => handleDateChange('全部日期')}
            style={{
              padding: '8px 12px',
              fontSize: '14px',
              color: '#999',
              whiteSpace: 'nowrap',
              cursor: 'pointer'
            }}
          >
            全部日期
          </div>
          <div 
            onClick={() => handleDateChange('周一 今日')}
            style={{
              padding: '8px 12px',
              fontSize: '14px',
              color: selectedDate === '周一 今日' ? '#fff' : '#999',
              background: selectedDate === '周一 今日' ? '#1677ff' : 'transparent',
              borderRadius: '4px',
              whiteSpace: 'nowrap',
              cursor: 'pointer'
            }}
          >
            周一 今日
          </div>
          <div 
            onClick={() => handleDateChange('周二 29')}
            style={{
              padding: '8px 12px',
              fontSize: '14px',
              color: '#999',
              whiteSpace: 'nowrap',
              cursor: 'pointer'
            }}
          >
            周二 29
          </div>
          <div 
            onClick={() => handleDateChange('周三 30')}
            style={{
              padding: '8px 12px',
              fontSize: '14px',
              color: '#999',
              whiteSpace: 'nowrap',
              cursor: 'pointer'
            }}
          >
            周三 30
          </div>
          <div 
            onClick={() => handleDateChange('周四 31')}
            style={{
              padding: '8px 12px',
              fontSize: '14px',
              color: '#999',
              whiteSpace: 'nowrap',
              cursor: 'pointer'
            }}
          >
            周四 31
          </div>
          <div 
            onClick={() => handleDateChange('周五 1')}
            style={{
              padding: '8px 12px',
              fontSize: '14px',
              color: '#999',
              whiteSpace: 'nowrap',
              cursor: 'pointer'
            }}
          >
            周五 1
          </div>
        </div>
      </div>

      {/* 医生列表 */}
      <div style={{ padding: '0 16px' }} onClick={()=>nav('/pai')}>
        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
            加载中...
          </div>
        ) : doctorList.length > 0 ? (
          doctorList.map((doctor: Doctor, index: number) => {
            const name = doctor?.doctorname || doctor?.name || '医生';
            const avatar = doctor?.doctorimage || doctor?.avatar || 'https://via.placeholder.com/60x60';
            const title = doctor?.doctortitle || doctor?.doctorstate || '';
            const department = doctor?.socoadmin || doctor?.doctorministre || doctor?.department || '';
            const specialty = doctor?.specialty || '';
            const availableSlots = doctor?.availableSlots || 0;
            const isFullyBooked = doctor?.isFullyBooked || false;

            return (
              <div
                key={doctor.doctorid || doctor.id || index}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  padding: '16px 0',
                  borderBottom: '1px solid #f0f0f0',
                  gap: '12px'
                }}
              >
                {/* 医生头像 */}
                <img
                  src={avatar}
                  alt="医生头像"
                  style={{
                    width: '60px',
                    height: '60px',
                    borderRadius: '50%',
                    objectFit: 'cover'
                  }}
                />

                {/* 医生信息 */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    marginBottom: '4px'
                  }}>
                    <div style={{
                      fontSize: '16px',
                      fontWeight: 600,
                      color: '#333'
                    }}>
                      {name}
                    </div>
                    <span style={{
                      fontSize: '14px',
                      color: '#999'
                    }}>
                      {title}
                    </span>
                  </div>

                  {/* 科室信息 */}
                  <div style={{
                    fontSize: '14px',
                    color: '#999',
                    marginBottom: '4px'
                  }}>
                    {department}
                  </div>

                  {/* 擅长领域 */}
                  <div style={{
                    fontSize: '14px',
                    color: '#666',
                    lineHeight: '1.4'
                  }}>
                    擅长: {specialty}
                  </div>
                </div>

                {/* 预约状态按钮 */}
                <div style={{ minWidth: '80px', textAlign: 'right' }}>
                  <div
                    onClick={() => handleAppointment(doctor)}
                    style={{
                      padding: '8px 12px',
                      fontSize: '14px',
                      color: '#fff',
                      background: isFullyBooked ? '#ff4d4f' : '#1677ff',
                      borderRadius: '4px',
                      cursor: isFullyBooked ? 'default' : 'pointer',
                      textAlign: 'center'
                    }}
                  >
                    {isFullyBooked ? '已约满' : `余${availableSlots}号`}
                  </div>
                </div>
              </div>
            );
          })
        ) : (
          <div style={{
            textAlign: 'center',
            padding: '40px 0',
            color: '#999'
          }}>
            暂无医生数据
          </div>
        )}
      </div>
    </div>
  );
}

export default Index;
